import store from '../utils/store'
// 临时测试用HTTP（仅开发者工具，真机需要HTTPS）
const SERVER_BASE = 'http://49.235.60.148:3000/api/miniprogram/'
// 生产环境需要HTTPS
// const SERVER_BASE = 'https://yourdomain.com/api/miniprogram/'

let flag = 0
async function handleTokenExpreir(method, options, resolve, reject) {
  const refreshToken = wx.getStorageSync('refreshToken')
  if (!refreshToken) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
   return reject()
  }
    const data = await request('refresh-token', {
      method: 'POST',
      data: {
        refreshToken: refreshToken
      }
    })
    getApp().globalData.token = data.accessToken
    wx.setStorageSync('token', data.accessToken)
    wx.setStorageSync('refreshToken', data.refreshToken)
    resolve(await request(method, options))
}

export default function request(
  url, 
  options, 
  globalLoading = true, 
  catchFail = true
) {
  const {token, deviceId} = getApp() ? getApp().globalData : {}
  options.data = {
    ...options.data
  }
  const loadingKey = url.split('/')[2]
  store.loading[loadingKey] = true
  if (globalLoading) {
    getApp().showLoading()
  }
  return new Promise((resolve, reject) => {
    wx.request({
      timeout: 1000 * 60,
      url: SERVER_BASE + url,
      ...options,
      header: {
        'Authorization': token ? `Bearer ${token}` : null,
        'X-Device-Id': deviceId
      },
      success: (res) => {
        console.log(url,res.data.code,res.data)

        if (res.data?.code === 200) {
          return resolve(res.data.data)
        }
        if ([400, 402].includes(res.data.code) && flag < 1) {
          flag ++
          resolve(handleTokenExpreir(url, options, resolve, reject))
        }
        if (res.data.code === 401) {
          wx.removeStorageSync('token')
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }
        reject(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        store.loading[loadingKey] = false
        if (globalLoading) {
          getApp().hideLoading()
        }
      }
    })
  }).catch((err) => {
    let { message, code } = err
    console.log(err)
    if (!message) {
      message = '网络请求失败'
    }
    if (code === 1001) {
      wx.showModal({
        title: '用户不存在',
        content: '您不是系统用户，无法使用此小程序',
        showCancel: false,
        success: () => {
          // 关闭小程序
          wx.exitMiniProgram();
        }
      });
      throw new Error(message)
    }
    if (code === 403) {
      wx.showModal({
        title: '登录失败',
        content: message,
        showCancel: false,
        success: () => {
          // 关闭小程序
          wx.exitMiniProgram();
        }
      });
      throw new Error(message)
    }
    if (catchFail) {
      getApp().showToast(message)
    }
    throw new Error(message)
  })
}
